package AccessDB;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import model.Disciplina;
import model.Materia;
import model.Professor;

public class DisciplinaDAO {
	
	Connection con;
	
	public DisciplinaDAO(){
		con = ConnectionDB.getInstance().getConnection();
	}
	
	public List<Disciplina> retonaDisciplinasDaTurma(int idTurma) throws SQLException{
		
		PreparedStatement stmt = con.prepareStatement("select * from Disciplina inner join Materia on Disciplina.idMateria = Materia.idMateria where idTurma = ?");
		stmt.setInt(1, idTurma);
		stmt.execute();
		
		ResultSet rs = stmt.getResultSet();
		
		List<Disciplina> disciplinas = new ArrayList<Disciplina>();
		
		while(rs.next()){
			disciplinas.add(gerarDisciplina(rs));
		}
		
		return disciplinas;
	}
	
	//Adicionado por Rui e Matheus
	public void cadastrarDisciplina(int idMateria, int idTurma) throws SQLException
	{
		PreparedStatement stmt = con.prepareStatement("insert into Disciplina values (?,?)");
		stmt.setInt(1, idMateria);
		stmt.setInt(2, idTurma);
		
		stmt.execute();
	}
	
	//Adicionado por Rui 26/12/09
	public Disciplina retornaDisciplina(int idDisciplina) throws SQLException
	{
		PreparedStatement stmt = con.prepareStatement("select * from Disciplina where idDisciplina = ?");
		stmt.setInt(1, idDisciplina);
		
		ResultSet rs = stmt.executeQuery();
		
		rs.next();
		return this.gerarDisciplina(rs);
		
	}
	
	private Disciplina gerarDisciplina(ResultSet rs) throws SQLException{
		
		Disciplina disciplina = new Disciplina();
		List<Professor> professores;
	
		disciplina.setIdDisciplina(Integer.parseInt(rs.getString("idDisciplina")));
		disciplina.setIdTurma(Integer.parseInt(rs.getString("idTurma")));
		Materia materia  = new MateriaDAO().retornaMateria(Integer.parseInt(rs.getString("idMateria")));
		disciplina.setMateria(materia);
		professores = new DisciplinaProfessorDAO().retornaProfessoresDaDisciplina(disciplina.getIdDisciplina());
		disciplina.setProfessores(professores);			
		
		return disciplina;
	}
	
	public List<Integer> retornaIdsDisciplinaProf(int idDisciplina) throws SQLException{
		
		PreparedStatement stmt = con.prepareStatement("select idDisciplinaProf from Disciplina " +
				"inner join DisciplinaProf on Disciplina.idDisciplina = DisciplinaProf.idDisciplina " +
				"where Disciplina.idDisciplina = ?");
		stmt.setInt(1, idDisciplina);
		ResultSet rs = stmt.executeQuery();
		
		List<Integer> ids = new ArrayList<Integer>();
		
		while(rs.next())
			ids.add(rs.getInt("idDisciplinaProf"));
		
		return ids;
	}
}